#include "SteamConnector.h"
#include <QXmlInputSource>

#include <QDebug>

#include "data/Config.h"
#include "GameListXmlHandler.h"
#include "AchievementListXmlHandler.h"

SteamConnector::SteamConnector(QObject *parent) :
    QObject(parent)
{
    m_nam = new QNetworkAccessManager();
    connect(m_nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(gotReply(QNetworkReply*)));
    m_steamId = Config::getInstance()->steamId();

}

void SteamConnector::start()
{
    // http://steamcommunity.com/id/baroach/games?tab=all&xml=1
    QString steamUrl = "http://steamcommunity.com/id/" + m_steamId + "/games?tab=all&xml=1";

    QNetworkRequest request;
    request.setUrl(QUrl(steamUrl));
    m_nam->get(request);


}

void SteamConnector::gotReply(QNetworkReply *reply)
{
    if (m_achievementRequestMap.contains(reply))
    {
        achievementListReply(reply);
    }
    else
    {
        gameListReply(reply);
    }

}

void SteamConnector::gameListReply(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        QXmlInputSource is;
        QXmlSimpleReader reader;
        GameListXmlHandler *handler = new GameListXmlHandler();

        is.setData(reply->readAll());
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);

        bool rc = reader.parse(is);

        if (rc)
        {
            m_gameMap = handler->games();



            QMapIterator<QString, Game> i(m_gameMap);
            while (i.hasNext())
            {
                i.next();
                // http://steamcommunity.com/id/baroach/stats/L4D2?tab=achievements&xml=1

                if (i.value().statsUrl().compare("") != 0)
                {
                    QNetworkRequest request;
                    request.setUrl(QUrl(i.value().statsUrl()));
                    QNetworkReply *reply2 = m_nam->get(request);
                    m_achievementRequestMap.insert(reply2, i.value().name());
                }
            }



        }
        else
        {
            qDebug() << "Parsing failed in SteamConnector::gameListReply()";
        }

        delete handler;

    }
    else
    {
        qDebug() << "SteamConnector::gameListReply(); QNetworkReply failed: " << reply->errorString();
    }

    reply->deleteLater();
}

void SteamConnector::achievementListReply(QNetworkReply *reply)
{
    m_achievementRequestMap.take(reply);

    if (reply->error() == QNetworkReply::NoError)
    {
        QXmlInputSource is;
        QXmlSimpleReader reader;
        AchievementListXmlHandler *handler = new AchievementListXmlHandler();

        is.setData(reply->readAll());
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);

        bool rc = reader.parse(is);

        if (rc)
        {
            QMap<QString, Achievement> aMap = handler->achievements();
            Game game = m_gameMap.value(handler->gameName());
            game.addAchievement(aMap);
            m_gameMap.insert(handler->gameName(),game);
            //qDebug() << "Game Name: " << handler->gameName();
        }

    }
    else
    {
        qDebug() << "SteamConnector::achievementListReply(); QNetworkReply failed: " << reply->errorString();
    }

    reply->deleteLater();

    if (m_achievementRequestMap.empty())
    {
        // we have all the achievements.
        emit receivedSteamData(m_gameMap);
    }

}
